<template>
  <div>


    <el-dialog :title="title" :visible.sync="dialogvisible" width="750px" append-to-body class="my-dialog"
               :close-on-click-modal="false" @close="cancel">
      <el-form ref="form" :model="form" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="执勤点名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入执勤点名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执勤点类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择执勤点类型"
                class="w100"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_stagnation_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属项目" prop="name">
              <el-select
                :style="{width: '100%'}"
                v-model="form.projectId"
                filterable
                remote
                :disabled="deptStatus"
                reserve-keyword
                placeholder="请输入所属项目关键词"
                @change="projectChange"
                :remote-method="remoteMethod_project"
                :loading="loading_project">
                <el-option
                  v-for="item in project_list"
                  :key="item.id"
                  :label="item.name || '未知'"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入驻日期" prop="inTime">
              <el-date-picker
                v-model="form.inTime"
                class="w100"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="province">
              <el-input v-model="form.inAddress" placeholder="自动识别" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执勤点地址" prop="address">
              <el-input
                v-model="form.address"
                type="textarea"
                maxlength="100"
                show-word-limit
                placeholder="请输入详细地址"
                @change="handleChangeAddress"
              />
              <!--              <el-select-->
              <!--                :style="{width: '100%'}"-->
              <!--                v-model="address"-->
              <!--                filterable-->
              <!--                remote-->
              <!--                reserve-keyword-->
              <!--                placeholder="请输入关键词"-->
              <!--                :remote-method="remoteMethod"-->
              <!--                :loading="loading">-->
              <!--                <el-option-->
              <!--                  v-for="item in options"-->
              <!--                  :key="item.id"-->
              <!--                  :label="item.address || '未知'"-->
              <!--                  :value="item.id">-->
              <!--                </el-option>-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="mapBox mb5">
              <div class="points-map__tip">在地图上双击获取执勤点地址 <span @click="showMapArea()" class="mapClick">点击绘制区域区间</span>
              </div>
              <div class="points-map" id="amap"></div>
            </div>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="围栏半径" prop="distance">-->
<!--              &lt;!&ndash; <el-input v-model="form.pointsRaduis" placeholder="围栏半径" /> &ndash;&gt;-->
<!--              <el-input-number-->
<!--                v-model="form.distance"-->
<!--                controls-position="right"-->
<!--                :min="0"-->
<!--                :max="10000"-->
<!--                placeholder="围栏半径/米"-->
<!--              />-->
<!--              米,已绘制区域区间可不填,根据区域区间进行判定-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <!--          <el-col :span="24">-->
          <!--            <div class="point-radius">-->
          <!--              &lt;!&ndash; 围栏半径 &ndash;&gt;-->
          <!--              <el-progress-->
          <!--                :percentage="((form.distance || 0) / 10000) * 100"-->
          <!--                :stroke-width="8"-->
          <!--                :show-text="false"-->
          <!--                color="#6D6D6D"-->
          <!--                define-back-color="#D9D9D9"-->
          <!--              ></el-progress>-->
          <!--              <div class="point-radius__len">-->
          <!--                <div class="point-radius__start">0米</div>-->
          <!--                <div class="point-radius__end">（10000米）10公里</div>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="所在派出所" prop="policeStation">-->
<!--              <el-input v-model="form.policeStation" placeholder="请输入所在派出所"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="派出所地址" prop="policeAddress">-->
<!--              <el-input v-model="form.policeAddress" placeholder="请输入派出所地址"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="派出所联系人" prop="policeName">-->
<!--              <el-input v-model="form.policeName" placeholder="请输入派出所联系人"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="派出所电话" prop="policePhone">-->
<!--              <el-input v-model="form.policePhone" placeholder="请输入派出所电话"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="村/居委会" prop="committee">-->
<!--              <el-input v-model="form.committee" placeholder="请输入村/居委会"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="办公室码" prop="code">-->
<!--              <el-input v-model="form.code" placeholder="请输入办公室码"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                maxlength="100"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
        <el-button @click="cancel" size="small" plain>取 消</el-button>
      </div>
    </el-dialog>
    <MapArea :visible.sync="mapVisible" :form="form" @getPoint="getPoint"></MapArea>
  </div>
</template>

<script>
import {
  addStagnationPoint,
  updateStagnationPoint,
  getStagnationPoint
} from "@/api/system/stagnation_point";
import {
  listProject,
  getProject
} from "@/api/system/project";
import MapArea from "@/components/MapArea"

export default {
  props: ['visible', 'paramDept', 'paramId'], // param 执勤点信息
  name: "index",
  dicts: ['sys_stagnation_type'],
  components: {MapArea},
  data() {
    return {
      dialogvisible: false,
      form: {},
      loading_zhudian: false,
      loading_user: false,
      auto: null,
      aMap: null,
      geocoder: null,
      marker: null,
      title: '新增执勤点信息',
      project_list: [],
      loading_project: false,
      deptStatus: false,
      mapVisible: false,
      polyline: null
    }
  },
  watch: {
    visible() {
      this.dialogvisible = this.visible
      this.reset()
      if (this.visible) {
        // param 执勤点信息
        let that = this
        if (this.paramDept) {
          this.project_list = [{
            id: this.paramDept.id.toString(),
            name: this.paramDept.name
          }]
          this.deptStatus = true
          this.form.projectId = this.paramDept.id
        }
        if (this.paramId) {
          getStagnationPoint(this.paramId).then(response => {
            response.data.detail.type = response.data.detail.type.toString()
            response.data.detail.projectId = response.data.detail.projectId.toString()
            this.form = response.data.detail;
            if (!this.paramDept) {
              this.getProject(response.data.detail.projectId)
            }
            this.title = "编辑执勤点信息";
            this.$nextTick(() => {
              that.createMap()
            })
          });
        } else {
          this.$nextTick(() => {
            that.createMap()
          })
        }
      }
    }
  },
  methods: {
    showMapArea() {
      this.mapVisible = true
    },
    // 所属项目
    remoteMethod_project(query) {
      this.loading_project = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
        name: query
      }
      listProject(query_).then(response => {
        this.project_list = response.rows;
        this.loading_project = false
      });
    },
    projectChange(option) {
      if (!option) {
        this.form.customId = ''
        return
      }
      for (let item of this.project_list) {
        if (item.id == option) {
          this.form.customId = item.customId
        }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: '', // 项目id
        customId: '', // 客户ID
        name: undefined,
        type: undefined,
        address: undefined, // 详细地址
        inAddress: undefined, // 所在地区
        fencePoints: undefined,
        inTime: undefined,
        policeStation: undefined, // 所属派出所
        policeAddress: undefined, // 派出所地址
        policeName: undefined, // 派出所联系人
        policePhone: undefined, // 派出所电话
        committee: undefined, // 居委会
        code: undefined, // 办公室码
        status: '0',
        remark: undefined, // 备注
        lat: '',
        lon: '',
        distance: 0, // 距离/米
        rangePoints: ''
      };
      this.resetForm("form");
      this.aMap = null
      this.geocoder = null
      this.marker = null
      this.project_list = []
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateStagnationPoint(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$emit('getList')
              this.cancel();
            });
          } else {
            addStagnationPoint(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit('getList')
              this.cancel();
            });
          }
        }
      });
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    // 创建地图
    createMap(quety, data) {
      const that = this
      this.aMap = new AMap.Map('amap', {
        mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        resizeEnable: true,
        center: quety == 'detail' ? [data.lon, data.lat] : that.$MapCenter,
        zoom: quety == 'detail' ? 16 : that.$MapZoom
      })
      this.geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 1000 //范围，默认：500
      });
      this.auto = new AMap.AutoComplete(this.autoOptions);
      this.marker = new AMap.Marker();
      this.aMap.on('dblclick', function (e) {
        that.setAddress(e.lnglat, 'dblclick')
      });
      if (quety == 'detail') {
        this.aMap.add(that.marker);
        this.marker.setPosition([parseFloat(data.lon), parseFloat(data.lat)]);
      }
      if (this.paramId) {
        that.setAddress({lng: this.form.lon, lat: this.form.lat}, 'edit')
      }
      if (this.form.rangePoints) {
        this.getPoint(this.form.rangePoints)
      }
    },
    // 地图搜索
    remoteMethod(query) {
      if (query !== '') {
        const that = this
        that.auto.search(query, function (status, result) {
          if (status === 'complete' && result.tips.length) {
            that.setAddress({
              lng: result.tips[0].location.lng, lat: result.tips[0].location.lat
            }, 'search')
          } else {
            that.$message.error('根据地址查询位置失败');
          }
        })
      } else {
        this.options = [];
      }
    },
    setAddress(lnglat, type) {
      const that = this
      that.aMap.add(that.marker);
      that.marker.setPosition([lnglat.lng, lnglat.lat]);
      if (type == 'search' || type == 'edit') {
        that.aMap.setCenter([lnglat.lng, lnglat.lat])
        that.aMap.setZoom(16)
      }
      that.geocoder.getAddress([lnglat.lng, lnglat.lat], function (status, result) {
        if (status === 'complete' && result.regeocode) {
          const address = result.regeocode.formattedAddress;
          const city_ = result.regeocode.addressComponent
          if (type !== 'search') {
            that.form.address = address
          }
          that.form.inAddress = `${city_.province}${city_.city}${city_.district}`
          that.currAdress = address // 当前的地址
          that.form.lat = lnglat.lat
          that.form.lon = lnglat.lng
        } else {
          that.$message.error('根据经纬度查询地址失败')
        }
      });
    },
    handleChangeAddress(value) {
      if (this.aMap && value !== this.currAdress) {
        this.remoteMethod(value)
      }
    },
    getProject(id) {
      getProject(id).then(res => {
        this.project_list = [{
          id: id,
          name: res.data.detail.name
        }];
      })
    },
    getPoint(item) {
      // 获取到的坐标
      console.log('item:', item)
      if (this.polyline) {
        this.aMap.remove(this.polyline)
      }
      let polygonArray;
      polygonArray = JSON.parse(item); //构建多边形经纬度坐标数组
      let arr = [];
      for (let j = 0; j < polygonArray.length; j++) {
        let ob = polygonArray[j];
        arr.push(new AMap.LngLat(ob.lng, ob.lat));
      }
      let zIndex = 10;
      this.polyline = new AMap.Polygon({
        map: this.map,
        path: arr,
        zIndex: zIndex,
        strokeColor: "#555",
        strokeOpacity: 0.5,
        strokeWeight: 1.5,
        // fillColor: strokeColor,
        fillOpacity: 0.35
      });
      this.polyline.setMap(this.aMap);
      this.form.rangePoints = item
    }
  }
}
</script>

<style scoped>
.points-map {
  height: 400px;
}

.points-map__tip {
  color: #010101;
  font-size: 14px;
  font-weight: 700;
  line-height: 20px;
}

.mapBox {
  margin-bottom: 20px;
  padding: 0 20px;
}

.mapClick {
  margin-left: 10px;
  color: #2a99ff;
  cursor: pointer;
}

.mapClick:hover {
  text-decoration: underline;
}
</style>
